<?php

namespace App\Http\Controllers;

use App\Models\Application;
use Exception;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    protected ?Application $application = null;

    /**
     * Notes   : 微信客户端环境检测
     *
     * @Date   : 2024/7/19 下午1:53
     * @Author : <Jason.C>
     * @param  Request  $request
     * @throws Exception
     */
    protected function checkWechatAgent(Request $request): void
    {
        # 微信环境检测
        $userAgent = $request->header('user-agent');

        if (!preg_match('/MicroMessenger/i', $userAgent)) {
            throw new Exception('请在微信环境中打开');
        }
    }

    /**
     * @throws Exception
     */
    protected function initApplication(Request $request): void
    {
        $appKey = $request->app_key;
        $app = Application::where('app_key', $appKey)->first();

        if ($app->isDisabled()) {
            throw new Exception('当前应用不可用');
        }

        $this->application = $app;
    }

    /**
     * Notes   : 显示错误信息页面
     *
     * @Date   : 2024/7/18 下午5:24
     * @Author : <Jason.C>
     * @param  string  $message
     * @return View
     */
    protected function showError(string $message)
    {
        return view('error', [
            'error' => $message,
            'application' => $this->application,
            'callback' => request()->callback,
        ]);
    }
}
